﻿using System;
using System.Text;
using System.Collections.Generic;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using MementoWeb.Data;
using DefaultConnection;
using AutoPoco;
using AutoPoco.DataSources;
using AutoPoco.Engine;
using MementoWeb.Controllers;
using AutoPoco.Configuration;

namespace MementoWeb.Tests.Integration
{
    public class SqlDatePropertyConvention : ITypePropertyConvention
    {
        public void Apply(ITypePropertyConventionContext context)
        {
            context.SetSource<DateOfBirthSource>();
        }

        public void SpecifyRequirements(ITypeMemberConventionRequirements requirements)
        {
            requirements.Type(x => x == typeof(DateTime));
        }
    }

    [TestClass]
    public class CategoryGroupControllerTest
    {
        private IGenerationSessionFactory _factory = null;

        public CategoryGroupControllerTest()
        {
            AutomapperConfig.RegisterAutomapperMaps();
            _factory = AutoPocoContainer.Configure(x =>
            {
                x.Conventions(c =>
                {
                    c.Register<SqlDatePropertyConvention>();
                    c.UseDefaultConventions();
                });
                x.AddFromAssemblyContainingType<WorkLog>();
                x.Include<CategoryGroup>();
                x.Include<Category>();
                x.Include<WorkLog>()
                    .Setup(c => c.Description).Use<RandomStringSource>(5, 20)
                    .Setup(c => c.DateCreated).Value(DateTime.UtcNow)
                    .Setup(c => c.DateUpdated).Value(DateTime.UtcNow)
                    .Setup(c => c.Workdate).Use<DateOfBirthSource>();
            });
        }
        [TestMethod]
        public void GetCategoryGroups_ShouldIncludeCategories()
        {
            var dataRepository = new DataRepository();
            var session = _factory.CreateSession();

            var categoryGroup = session.Single<CategoryGroup>().Get();
            categoryGroup.Name = Guid.NewGuid().ToString();
            categoryGroup.Save();
            var category = session.Single<Category>().Get();
            category.CategoryGroupId = categoryGroup.CategoryGroupId;
            Assert.AreNotEqual(0, category.CategoryGroupId);
            category.Name = Guid.NewGuid().ToString();
            category.Save();
            CategoryGroupController categoryGroupController = new CategoryGroupController(dataRepository);
            var categoryGroups = categoryGroupController.Get();
            var categoryGroupWithThisName = categoryGroups.First(w => w.Name == categoryGroup.Name);
            Assert.AreEqual(1, categoryGroupWithThisName.Categories.Count());
            Assert.AreEqual(categoryGroupWithThisName.Categories.First().Name, category.Name);
        }
    }
}
